<?php

namespace app\admin\command;

use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\Env;

require_once('/usr/share/nginx/html/application/common/library/esl/ESL.php');

class TestESL extends Command
{

    //重连时间
    protected $reconnectInterval = 1000; //单位：毫秒

    protected $sentenceInterval = 3000; //话术间隔停顿时间，单位：毫秒

    protected $breakInterval = 501; //命中关键字后的停顿间隔时间，单位：毫秒

    protected $sock = NULL;

    //信道
    protected $asrSessions = array();

    //命令行初始化
    protected function configure()
    {
        $this->setName('testesl')
            ->setDescription('Test ESL');
    }

    //main函数
    protected function execute(Input $input, Output $output)
    {
        while (1) {
            $this->sock = new \ESLconnection('127.0.0.1', '8021', 'ClueCon');
            //$this->sock->sendRecv("event json CUSTOM asr");
            //$this->sock->sendRecv("event json CHANNEL_HANGUP_COMPLETE");
            //$this->sock->sendRecv("event json CHANNEL_EXECUTE_COMPLETE");
            $this->sock->sendRecv("event json ALL");
            if ($this->sock->connected()) {
                echo "ESL Connected!\n";
                while ($this->sock->connected()) {
                    $this->doLoop();
                }
            } else {
                $this->asrSessions = null;
                $this->asrSessions = array();
                usleep($this->reconnectInterval * 1000);
                echo "Reconnecting ESL ...\n";
            }
        }
    }

    //消息循环体
    protected function doLoop()
    {
        try {
            //usleep(1 * 1000 * 1000);
            //echo "\ntest\n";
            $event = $this->sock->recvEvent();
            //print_r($event->serialize('json'));
            $evt = $event->serialize('json');
            $evt = json_decode($evt, true);
            var_dump($evt);
            //unset($event->_cPtr);
            //$event = null;
            //unset($event);
            gc_collect_cycles();
                $real_mem_usage = memory_get_usage(true);
                $total_mem_usage = memory_get_usage(false);
                echo "\nMemory Usage(real): {$real_mem_usage} , (total): {$total_mem_usage}\n";

            return;
        } catch (Exception $e) {
            return;
        }
    }
}
